package com.film.filter;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.film.token.JwtUtil;

import io.jsonwebtoken.Claims;

/**
 * 用户登录
 * 
 * @author YH
 *
 */
@WebFilter("/*")
public class Login implements Filter {

	private static List<String> list;

	static {
		list = new ArrayList<>();
		list.add("/filminfo");
		list.add("/filmtype");
		list.add("/filmtypes");
		list.add("/filminfos");
	}

	public void destroy() {
	}

	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
			throws IOException, ServletException {
		System.out.println("");
		HttpServletRequest req = (HttpServletRequest) request;
		HttpServletResponse resp = (HttpServletResponse) response;
		String requestURI = req.getRequestURI();

		// 判断用户的状态
		String token = req.getParameter("token");

		if (token != null && !token.trim().equals("") && token.trim().length()>20) {
			System.out.println(token);
			JwtUtil jwtUtil = new JwtUtil();
			try {
				Claims parseJWT =null;
				
				try {
					 parseJWT = jwtUtil.parseJWT(token);
				} catch (Exception e) {
					resp.setStatus(401);
					return;
				}
				

				Date date = parseJWT.getIssuedAt();
				if (date.getTime() > new Date().getTime()) {
					resp.setStatus(401);
					return;
				}

				//用户登录成功
				
				String userid = parseJWT.getId();

				System.out.println(userid);

				chain.doFilter(request, response);
				return;

			} catch (Exception e) {
				e.printStackTrace();
			}
		}

		for (int i = 0; i < list.size(); i++) {
			if (requestURI.contains(list.get(i))) {
				resp.setStatus(401);
				return;
			}
		}
		chain.doFilter(request, response);
		return;
	}

	public void init(FilterConfig fConfig) throws ServletException {
	}

}
